<?php

if (is_numeric($_POST['ref_id']) and is_numeric($_POST['id'])) {
	// both ids are numeric
	if ($db->fetchOne("SELECT id FROM site_templates WHERE site_id=? AND id=?", array($site['id'], $_POST['ref_id'])) and $db->fetchOne("SELECT id FROM site_templates WHERE site_id=? AND id=?", array($site['id'], $_POST['id']))) {
		// both ids belong to this site
		$logger->debug($_POST['type']);
		
		$sort = $db->fetchOne("SELECT sort FROM site_templates WHERE id=?", $_POST['ref_id']);
		$sort = $_POST['type'] == 'after' ? $sort+5 : $sort-5;
		$db->update('site_templates', array('sort' => $sort), $db->quoteInto("id=?", $_POST['id']));
		// reassign sort x 10
		$template_ids = $db->fetchCol("SELECT id FROM site_templates WHERE site_id=? ORDER BY sort", $site['id']);
		for($i=0;$i<count($template_ids);$i++) {
			$db->update('site_templates', array('sort' => $i*10+10), "id={$template_ids[$i]}");
		}
		
		header('Content-type: application/json');
		echo json_encode(array('id' => $_POST['id']));
		
	}
	
}
